package com.overlord.im.server.resolver.message;

import com.baidu.fsg.uid.impl.DefaultUidGenerator;
import com.overlord.im.commons.constant.AckType;
import com.overlord.im.commons.message.OverlordImMessage;
import com.overlord.im.server.message.entity.ServerMessageEntity;
import com.overlord.im.server.message.service.ServerMessageService;
import com.overlord.im.server.mapstruct.MessageMapper;
import com.overlord.im.server.message.service.SendMessageService;
import com.overlord.im.server.resolver.MessageResolver;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @ClassName MsgRResolver
 * @Author wuwei
 * @Description NONE
 * @Date 2020/6/2 17:59
 **/
@Service
public class MsgrResolver implements MessageResolver<OverlordImMessage> {

    @Resource
    private MessageMapper messageMapper;

    @Resource
    private ServerMessageService serverMessageService;

    @Resource
    private SendMessageService sendMessageService;

    @Resource
    private DefaultUidGenerator defaultUidGenerator;

    @Override
    public boolean support(OverlordImMessage message) {
        return message.getAckType() == AckType.MSG_R;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resolve(OverlordImMessage message) {
        ServerMessageEntity entity = messageMapper.toServerMessage(message);
        entity.setSequenceId(defaultUidGenerator.getUID());
        //将消息发送至接收方
        sendMessageService.sendMsgN(message, entity);
        //返回发送方服务端已接收消息
        sendMessageService.sendMsgA(message, entity);
    }
}
